package com.ht.api.bigtask.impl.qywx;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import com.ht.api.bigtask.BaseBigTask;
import com.ht.api.constant.CustomerLinkStatus;
import com.ht.api.db.Db;
import com.ht.api.db.DbConfig;
import com.ht.api.db.Entity;
import com.ht.api.db.StreamLoadConfig;
import com.ht.api.open.OpenUtil;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 初始化：获取联系我列表
 * @author asq
 * @createTime 2025年4月2日 08:51:15
 */
@Slf4j
public class QueryContactWayList extends BaseBigTask {
	/** 接口ID：获取联系我列表 */
	private static final long API_ID_LIST = 1900130921173094400L;
	/** 接口ID：获取企业已配置的「联系我」方式 */
	private static final long API_ID_INFO = 1900130546936320000L;

	@Override
	protected void doExecute(String appId, JSONObject context, Entity bean) {
		DataSource ds = getTenantDs(appId);
		StreamLoadConfig streamLoadConfig = DbConfig.getStreamLoadConfigByDataSource(ds);
		String str = OpenUtil.call(appId, API_ID_LIST, JSONUtil.createObj().set("start_time", 1625846400).set("limit", 1000));
		JSONObject obj = JSONUtil.parseObj(str);
		if (obj.getInt("errcode") == 0) {
			List<Entity> list = new ArrayList<>();
			JSONArray contactWayArr = obj.getJSONArray("contact_way");
			
			for (int i = 0; i < contactWayArr.size(); i++) {
				JSONObject contactWay = contactWayArr.getJSONObject(i);
				String configId = contactWay.getStr("config_id");
				list.addAll(createContactWayByWwx(appId, configId));
			}
			
			Db.insertBatchWithStream(streamLoadConfig, list);			
			log.info("[QueryContactWayList]企微初始化，获取联系我列表，总数：{}", contactWayArr.size());
		} else {
			log.error("[QueryContactWayList]企微初始化，获取联系我列表时返回失败：{}", obj.getStr("errmsg"));
		}
	}
	
	/**
	 * 根据微信返回的config_id创建本地数据库中的Entity
	 * @param appId
	 * @param configId
	 * @return
	 */
	private List<Entity> createContactWayByWwx(String appId, String configId) {
		List<Entity> list = new ArrayList<>();
		String str = OpenUtil.call(appId, API_ID_INFO, JSONUtil.createObj().set("config_id", configId));
		JSONObject obj = JSONUtil.parseObj(str);
		if (obj.getInt("errcode") == 0) {
			JSONObject contactWay = obj.getJSONObject("contact_way");
			JSONArray userArr = contactWay.getJSONArray("user");
			
			// 创建联系我主表
			Entity wxContactWay = Db.createEntity("wx_contact_way");
			wxContactWay.set("appid", appId);
			wxContactWay.set("type", contactWay.getStr("type"));
			wxContactWay.set("scene", contactWay.getStr("scene"));
			wxContactWay.set("remark", contactWay.getStr("remark"));
			wxContactWay.set("skip_verify", contactWay.getBool("skip_verify") ? 1 : 0);
			wxContactWay.set("state", contactWay.getStr("state"));
			wxContactWay.set("style", contactWay.getStr("style"));
			if (contactWay.containsKey("is_exclusive")) {
				wxContactWay.set("is_exclusive", contactWay.getBool("is_exclusive") ? 1 : 0);
			} else {
				wxContactWay.set("is_exclusive", 0);
			}
			wxContactWay.set("friend_cnt", 0);
			wxContactWay.set("status", CustomerLinkStatus.ENABLED);
			wxContactWay.set("config_id", configId);
			wxContactWay.set("qr_code", contactWay.getStr("qr_code"));
			wxContactWay.set("user", userArr.toString());
			list.add(wxContactWay);
			
			// 创建关联表
			for (int i = 0; i < userArr.size(); i++) {
				String userid = userArr.getStr(i);
				Entity wxContactWayRelation = Db.createEntity("wx_contact_way_relation");
				wxContactWayRelation.set("contact_way_id", wxContactWay.getMainId());
				wxContactWayRelation.set("userid", userid);
				wxContactWayRelation.set("create_time", DateUtil.now());
				wxContactWayRelation.set("friend_cnt", 0);
				wxContactWayRelation.set("state", wxContactWay.getStr("state"));
				wxContactWayRelation.set("status", 0);
				list.add(wxContactWayRelation);
			}
		} else {
			log.error("[QueryContactWayList]企微初始化，获取联系我详情时返回失败：{}", obj.getStr("errmsg"));
		}
		return list;
	}

}
